package org.linlinjava.litemall.brand.annotation.support;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;
import org.linlinjava.litemall.brand.annotation.LoginUser;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;


public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "token";

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request.getNativeRequest();
        XxlSsoUser currentUser = (XxlSsoUser) req.getAttribute(Conf.SSO_USER);
        if (currentUser == null) {
            return ResponseUtil.fail(Conf.SSO_LOGIN_FAIL_RESULT.getCode(), Conf.SSO_LOGIN_FAIL_RESULT.getMsg());
        }
        return Integer.valueOf(currentUser.getUserid());
//        String token = request.getHeader(LOGIN_TOKEN_KEY);
//        if (token == null || token.isEmpty()){
//            return null;
//        }
//        return UserTokenManager.getUserId(token);
    }


}
